/*
 * ErrorDisplay.java
 *
 * Copyright (c) 2010 Jaymie Strecker (strecker at cs.umd.edu). All rights reserved.
 *
 * This file is part of Tonic.
 *
 * Tonic is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tonic is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Tonic.  If not, see <http://www.gnu.org/licenses/>.
 */

package tonic.gui;

import javax.swing.*;
import java.awt.Component;

/**
 *
 * @author Jaymie Strecker (strecker at cs.umd.edu)
 */
public class ErrorDisplay {

    public ErrorDisplay(Component parent, String message, Throwable e) {
        display(parent, message, e, true);
    }

    public ErrorDisplay(Component parent, String message, Throwable e, boolean recommendRestart) {
        display(parent, message, e, recommendRestart);
    }

    private void display(Component parent, String message, Throwable e, boolean recommendRestart) {
        String newLine = System.getProperty("line.separator");
        String stackTrace = "";
        String type = "";
        if (e != null) {
            StackTraceElement[] st = e.getStackTrace();
            for (int i = 0; i < st.length; i++) {
                stackTrace += st[i] + newLine;
            }
            type = e.getClass().getName();
        }
        String fullMessage = message;
        if (recommendRestart) {
            fullMessage += newLine + newLine +
                "It is recommended that you restart the program.";
        }
        fullMessage += newLine + newLine +
                "To copy text from this dialog, use Control-C (even on a Mac).";
        if (e != null) {
            fullMessage += newLine + newLine + type + newLine + stackTrace;
        }
        JTextArea messageArea = new JTextArea(fullMessage, 10, 40);
        messageArea.setEditable(false); 
        messageArea.setLineWrap(true);
        messageArea.setWrapStyleWord(true); 
        JScrollPane messageScroll = new JScrollPane(messageArea);
        JOptionPane.showMessageDialog(parent, messageScroll, "Error", JOptionPane.ERROR_MESSAGE);
    }

}
